from django.http import JsonResponse
from django.core.paginator import Paginator,EmptyPage, PageNotAnInteger
import json
from common.models import bill

def dispatcher(request):
    # if 'usertype' not in request.session:
    #     return JsonResponse({
    #         'ret': 302,
    #         'msg': '未登录'},
    #         status=302)
    #
    # if request.session['usertype'] != 'mgr':
    #     return JsonResponse({
    #         'ret': 302,
    #         'msg': '用户非mgr类型'},
    #         status=302)

    # 将请求参数统一放入request 的 params 属性中，方便后续处理

    # GET请求 参数在url中，同过request 对象的 GET属性获取
    if request.method == 'GET':
        request.params = request.GET
        # POST/PUT/DELETE 请求 参数 从 request 对象的 body 属性中获取
    elif request.method in ['POST','PUT','DELETE']:
        # 根据接口，POST/PUT/DELETE 请求的消息体都是 json格式
        request.params = json.loads(request.body)


    # 根据不同的action分派给不同的函数进行处理
    action = request.params['action']
    if action == 'list':
        return lists(request)
    elif action == 'listGuest':
        return listGuest(request)
    elif action == 'listBill':
        return listBill(request)
    elif action == 'listReceivedBill':
        return listReceivedBill(request)
    elif action == 'listGuestBill':
        return listGuestBill(request)
    elif action == 'listGuestReceivedBill':
        return listGuestReceivedBill(request)
    elif action == 'add':
        return add(request)
    elif action == 'modify':
        return modify(request)
    elif action == 'del':
        return delete(request)

    else:
        return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'})



def lists(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    # qs = user.objects.filter(is_delete=0).values()
    landlord_id = request.GET.get('user_id')
    # 先获取所有的一年级学生id列表
    list1 = bill.objects.filter(is_delete=0,landlord_id=landlord_id).values('id','room__Room_number','all_cost','water_cost','electricity_cost','network_cost','start_time','end_time')
    page = request.GET.get('pageNum')  # 获取页码
    pageSize = request.GET.get('pageSize')  #设置每页显示条数
    paginator = Paginator(list1, pageSize)
    response = {}
    # 获取数据总条数
    response['totalCount'] = paginator.count
    # 每页显示条数
    response['numPerPage'] = pageSize
    # 总共页数
    response['totalPage'] = paginator.num_pages
    # 获取指定页码的数据
    try:
        qs = paginator.page(page)
    except PageNotAnInteger:
        qs = paginator.page(1)
    except EmptyPage:
        qs = paginator.page(paginator.num_pages)
    response['pageNum'] = qs.number
    # 将 QuerySet 对象 转化为 list 类型
    # 否则不能 被 转化为 JSON 字符串
    response['retlist'] = list(qs.object_list)
    res = {}
    res['status'] = 1
    res['message'] = '获取成功'
    res['data'] = response
    return JsonResponse(res)

def listGuest(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    # qs = user.objects.filter(is_delete=0).values()
    guests_id = request.GET.get('guests_id')
    end_time = request.GET.get('end_time')
    # 先获取所有的一年级学生id列表
    list1 = bill.objects.filter(is_delete=0,guests_id=guests_id,end_time__contains=end_time).values('id','room__Room_number','all_cost','water_cost','electricity_cost','network_cost','start_time','end_time')
    res = {}
    res['status'] = 1
    res['message'] = '获取成功'
    res['data'] = list(list1)
    return JsonResponse(res)

def listReceivedBill(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    # qs = user.objects.filter(is_delete=0).values()
    landlord_id = request.GET.get('landlord_id')
    end_time = request.GET.get('end_time')
    # 先获取所有的一年级学生id列表
    list1 = bill.objects.filter(is_delete=0,landlord_id=landlord_id,end_time__contains=end_time,type=1).values('id','room__Room_number','all_cost','water_cost','electricity_cost','network_cost','start_time','end_time')
    res = {}
    res['status'] = 1
    res['message'] = '获取成功'
    res['data'] = list(list1)
    return JsonResponse(res)

def listBill(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    # qs = user.objects.filter(is_delete=0).values()
    landlord_id = request.GET.get('landlord_id')
    end_time = request.GET.get('end_time')
    # 先获取所有的一年级学生id列表
    list1 = bill.objects.filter(is_delete=0,landlord_id=landlord_id,end_time__contains=end_time,type=0).values('id','room__Room_number','all_cost','water_cost','electricity_cost','network_cost','start_time','end_time')
    res = {}
    res['status'] = 1
    res['message'] = '获取成功'
    res['data'] = list(list1)
    return JsonResponse(res)

def listGuestReceivedBill(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    # qs = user.objects.filter(is_delete=0).values()
    guests_id = request.GET.get('guests_id')
    end_time = request.GET.get('end_time')
    # 先获取所有的一年级学生id列表
    list1 = bill.objects.filter(is_delete=0,guests_id=guests_id,end_time__contains=end_time,type=1).values('id','room__Room_number','all_cost','water_cost','electricity_cost','network_cost','start_time','end_time')
    res = {}
    res['status'] = 1
    res['message'] = '获取成功'
    res['data'] = list(list1)
    return JsonResponse(res)

def listGuestBill(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    # qs = user.objects.filter(is_delete=0).values()
    guests_id = request.GET.get('guests_id')
    end_time = request.GET.get('end_time')
    # 先获取所有的一年级学生id列表
    list1 = bill.objects.filter(is_delete=0,guests_id=guests_id,end_time__contains=end_time,type=0).values('id','room__Room_number','all_cost','water_cost','electricity_cost','network_cost','start_time','end_time')
    res = {}
    res['status'] = 1
    res['message'] = '获取成功'
    res['data'] = list(list1)
    return JsonResponse(res)

def add(request):

    info  = request.params['data']

    # 从请求消息中 获取要添加客户的信息
    # 并且插入到数据库中
    # 返回值 就是对应插入记录的对象
    record = bill.objects.create(
        room_id=info['room_id'],
        guests_id=info['guests_id'],
        landlord_id=info['landlord_id'],
        all_cost=info['all_cost'],
        water_cost=info['water_cost'],
        electricity_cost=info['electricity_cost'],
        network_cost=info['network_cost'],
        start_time=info['start_time'],
        end_time=info['end_time'],
    )


    return JsonResponse({'ret': 0, 'id':record.id})


def modify(request):
    # 从请求消息中 获取修改客户的信息
    # 找到该客户，并且进行修改操作
    # print('123')
    customerid = request.params['id']
    newdata = request.params['newdata']

    try:
        # 根据 id 从数据库中找到相应的客户记录
        customer = bill.objects.get(id=customerid)
    except bill.DoesNotExist:
        return {
            'ret': 1,
            'msg': f'id 为`{customerid}`的客户不存在'
        }

    if 'all_cost' in newdata:
        customer.all_cost = newdata['all_cost']
    if 'water_cost' in newdata:
        customer.water_cost = newdata['water_cost']
    if 'electricity_cost' in newdata:
        customer.electricity_cost = newdata['electricity_cost']
    if 'network_cost' in newdata:
        customer.network_cost = newdata['network_cost']
    if 'start_time' in newdata:
        customer.start_time = newdata['start_time']
    if 'end_time' in newdata:
        customer.end_time = newdata['end_time']
    if 'type' in newdata:
        customer.type = newdata['type']
    if 'is_delete' in newdata:
        customer.is_delete = newdata['is_delete']
    # 注意，一定要执行save才能将修改信息保存到数据库
    customer.save()

    return JsonResponse({'ret': 0, 'msg': '更新成功','customerid':request.params['id']})

def delete(request):

    customerid = request.params['id']

    try:
        # 根据 id 从数据库中找到相应的客户记录
        customer = bill.objects.get(id=customerid)
    except bill.DoesNotExist:
        return  {
                'ret': 1,
                'msg': f'id 为`{customerid}`的客户不存在'
        }

    # delete 方法就将该记录从数据库中删除了
    customer.delete()

    return JsonResponse({'ret': 0})